import { HOST, PORT } from "./const";
import { useDeviceUuid } from "./useDeviceUuid";
import { useStorage } from "./useStorage";


export function httpPost<T = any>(url: string, postData: any, def: T | undefined = undefined): T {

    const token = useStorage().get('token', "")
    if (token) {
        postData['token'] = token;
    }
    const uuid = useDeviceUuid()
    if (uuid) {
        postData['uuid'] = uuid;
    }
    if (!url.startsWith('http')) {
        url = `http://${HOST}:${PORT}/autojs/core/autox/${url}`;
    }
    const res = http.post(url, postData, {
        timeout: 5000,
        contentType: 'application/json'
    }) as AutoJs.Response;
    if (res.statusCode !== 200) {
        if (def) return def;
        throw new Error(`httpPost error: ${res.statusCode} ${res.statusMessage}`);
    }
    const contentType: string = (res.headers as any)["Content-Type"] || "";
    if (contentType.includes("text/html")) {
        if (def) return def;
        throw new Error(`httpPost error: ${res.body}`);
    }
    const body = res.body.json();
    const { message, success, data } = body;
    if (success) return data;
    if (def) return def;
    throw new Error(`httpPost error: ${message}`);
}